//
//  ItemViewController.m
// 
//
//  Created by Jones on 11/27/16.
//  Copyright © 2016 Jones. All rights reserved.
//
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>

#import "ItemViewController.h"
#import "MKConstant.h"
#import "network.h"
#import "DB/DataPersist.h"

#import "aboutUs/UIScrollView的快速使用-Bridging-Header.h"
#import "UIScrollView的快速使用-Swift.h"

#import "contactTVC2.h"

@interface ItemViewController ()<WKNavigationDelegate,WKUIDelegate>{
    NSData *itemHTMLData;
    
     contactTVC2 *contvc2;
    //network *getdata;
//    UIScrollView *sv_image;
//    UIPageControl *pageControl;
//    NSTimer *timer;
//    int imageIndex;
//    StarRateView *starRateView;
//    UILabel *lab_currentScore;
}
@property (strong, nonatomic)   WKWebView                   *webView;
@property (strong, nonatomic)   UIProgressView              *progressView;
@end

@implementation ItemViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
   
    // 颜色
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor whiteColor];
    //NSString *title = self.itemDatasource.title;
    //NSString *title = @"1";
    //NSString *title = self.itemDatasource;
    //self.navigationItem.title = title;  //设置navigationItem.title 标题
    [self.navigationController.navigationBar setTitleTextAttributes:@{
       NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor grayColor]                }];
    
    //网络初始化
    //等网络请求 通知后再加载数据
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setitemdata) name:@"getitemDataNOTIF" object:nil];
    
    network *getdata = [[network alloc]init];
    [getdata itemVcgetJsonData:@"id" item:self.itemDatasource];  //获取子页面数据
    [self loadingView];  //等待网络结果动画
    
    
    // sv 空白
//    self.automaticallyAdjustsScrollViewInsets = false;
//    UIView *view_head = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH*0.6)];
//    view_head.backgroundColor = [UIColor whiteColor];
//    [self.view addSubview:view_head];
    
//    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(rightClick)];
//    self.navigationItem.rightBarButtonItem = rightItem;
    
   // [self setitemdata];  不等网络请求直接加载数据
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setitemdata{
    //读取数组值
    NSMutableArray *itemArray = [[DataPersist readValueNSMutableArray:@"itemData"] mutableCopy];
    //NSLog(@"itemArray %@ ",itemArray);
    
    NSString *banner = [itemArray valueForKey:@"banner"];
    //NSLog(@"banner is %@",banner);
    
    NSDictionary *itemdata = [itemArray valueForKey:@"data"];
    //NSLog(@"itemdata is %@",itemdata);
    
    NSString *post_content = [itemdata valueForKey:@"post_content"];
    //NSLog(@"post_content is %@",post_content);
    
    NSMutableString *headHTML = [NSMutableString string];  //加载本地CSS js
    [headHTML appendString:@"<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\">"];
    [headHTML appendFormat:@"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"%@\" />",[[NSBundle mainBundle] URLForResource:@"style" withExtension:@"css"]];
    
     [headHTML appendFormat:@"<link rel=\"stylesheet\" type=\"text/css\" media=\"all\" href=\"%@\" />",[[NSBundle mainBundle] URLForResource:@"w3" withExtension:@"css"]];
    
    [headHTML appendString:@"</head><body>"];
    

    banner = [headHTML stringByAppendingString:banner]; //合并banner 和 post_content
    
    NSString *str2 = [banner stringByAppendingString:post_content]; //合并banner 和 post_content
    //NSLog(@"str2 is %@",str2);
    
    
    itemHTMLData = [str2 dataUsingEncoding:NSUTF8StringEncoding];
    
    //banner
//    homebannerarr = [dataarr valueForKey:@"homeBanner"];
//    NSLog(@"homeBannerarr is %@",homebannerarr);
//    //NSLog(@"imgbanner url %@",homebannerarr[1]);
//
//    //字典   包含数组
//    NSMutableArray *aceServicesarr = [dataarr valueForKey:@"aceServices"];
//    NSArray *arra = [self setnewarr:aceServicesarr cate:@"aceServices"];
//    //NSLog(@"arra %@",arra);
//
//    NSMutableArray *healthManagementarr = [dataarr valueForKey:@"healthManagement"];
//    NSArray *arrb = [self setnewarr:healthManagementarr cate:@"healthManagement"];
//
//
//    NSMutableArray *menuarr2 = [[NSMutableArray alloc]init]; //菜单数组新建
//    [menuarr2 addObject:arra];
//    [menuarr2 addObject:arrb];
    //NSLog(@"menuarr.count %lu",(unsigned long)menuarr2.count);
    
    //menuarr = [menuarr2 mutableCopy];
    
    //NSLog(@"menuarr.count %lu",(unsigned long)menuarr.count);
    //NSLog(@"menuarr %@",menuarr2);
    
    
    //NSLog(@"第一次读取的值MACArray value is:%@",MACArray);
    
    //        NSMutableArray *dataarr = [MACArray valueForKey:@"data"];
    //
    //    NSString *item3 = [homeBannerarr firstObject];
    //    //NSLog(@"item3  %@",item3);
    //    [DataPersist writeValuePre:item3 key:@"banner1"];
    
    [self startInitWKWebView];
}

- (void)startInitWKWebView
{
    [self initWKWebView];
    
    [self initProgressView];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self bookingview]; //立刻预约页面
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)initWKWebView
{
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [WKUserContentController new];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    //preferences.minimumFontSize = 30.0;
    preferences.minimumFontSize = 0.0f; //WkWebView中H5的UI向下偏移的问题
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
    
    //直接网络请求
    //NSString *urlStr = @"http://www.baidu.com";
//    NSString *title = self.itemDatasource;
//    NSString *urlStr = @"http://youngplus.com.hk/app-get-service-detail?id=";
//    urlStr = [urlStr stringByAppendingString:title];
//    NSLog(@"urlStr : %@",urlStr);
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
//    [self.webView loadRequest:request];
    
    
//    NSData *data = self.itemDatasource;
//
//    // 将请求到的网页数据用loadHTMLString 的方法加载
    NSString *htmlStr = [[NSString alloc] initWithData:itemHTMLData encoding:NSUTF8StringEncoding];
    
    NSURL *baseUrl = [NSURL URLWithString:@"file:///assets/"];
    //[self.webView loadHTMLString:[self.viewModel getHtmlString] baseURL:baseUrl];
    [self.webView loadHTMLString:htmlStr baseURL:baseUrl];
    
 
    //本地文件请求
    //    NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
    //    NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
    //    [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
    
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
    
//    [loadActivity stopAnimating];
//    [activityBg removeFromSuperview];
//    [self dismissViewControllerAnimated:true completion:nil];
}

- (void)initProgressView
{
    CGFloat kScreenWidth = [[UIScreen mainScreen] bounds].size.width;
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 2)];
    progressView.tintColor = [UIColor redColor];
    progressView.trackTintColor = [UIColor lightGrayColor];
    [self.view addSubview:progressView];
    self.progressView = progressView;
}





- (void)rightClick
{
    [self goBack];
}

- (void)dealloc
{
    NSLog(@"%s",__FUNCTION__);
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    // 销毁通知
   [[NSNotificationCenter defaultCenter]removeObserver:self name:@"getitemDataNOTIF" object:nil];
    
}



- (void)getLocation
{
    // 获取位置信息
    
    // 将结果返回给js
    NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"广东省深圳市南山区学府路XXXX号"];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
    
}

- (void)share:(NSURL *)URL
{
    NSArray *params =[URL.query componentsSeparatedByString:@"&"];
    
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    for (NSString *paramStr in params) {
        NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
        if (dicArray.count > 1) {
            NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [tempDic setObject:decodeValue forKey:dicArray[0]];
        }
    }
    
    NSString *title = [tempDic objectForKey:@"title"];
    NSString *content = [tempDic objectForKey:@"content"];
    NSString *url = [tempDic objectForKey:@"url"];
    // 在这里执行分享的操作
    
    // 将分享结果返回给js
    NSString *jsStr = [NSString stringWithFormat:@"shareResult('%@','%@','%@')",title,content,url];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
}

- (void)changeBGColor:(NSURL *)URL
{
    NSArray *params =[URL.query componentsSeparatedByString:@"&"];

    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    for (NSString *paramStr in params) {
        NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
        if (dicArray.count > 1) {
            NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [tempDic setObject:decodeValue forKey:dicArray[0]];
        }
    }
    CGFloat r = [[tempDic objectForKey:@"r"] floatValue];
    CGFloat g = [[tempDic objectForKey:@"g"] floatValue];
    CGFloat b = [[tempDic objectForKey:@"b"] floatValue];
    CGFloat a = [[tempDic objectForKey:@"a"] floatValue];

    self.view.backgroundColor = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a];
}

- (void)payAction:(NSURL *)URL
{
    NSArray *params =[URL.query componentsSeparatedByString:@"&"];

    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    for (NSString *paramStr in params) {
        NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
        if (dicArray.count > 1) {
            NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [tempDic setObject:decodeValue forKey:dicArray[0]];
        }
    }
    //    NSString *orderNo = [tempDic objectForKey:@"order_no"];
    //    long long amount = [[tempDic objectForKey:@"amount"] longLongValue];
    //    NSString *subject = [tempDic objectForKey:@"subject"];
    //    NSString *channel = [tempDic objectForKey:@"channel"];

    // 支付操作

    // 将支付结果返回给js
    NSString *jsStr = [NSString stringWithFormat:@"payResult('%@', 1)",@"支付成功"];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
}

- (void)shakeAction
{
    AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
}

- (void)goBack
{
    [self.webView goBack];
}

#pragma mark - KVO
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
                [self.progressView setProgress:0 animated:NO];
            });
            
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"拦截点击");
//    NSURL *URL = navigationAction.request.URL;
//    NSString *scheme = [URL scheme];
//    NSLog(@"请求连接  ,%@",scheme);
//
//    if ([scheme isEqualToString:@"haleyaction"]) {
//
//        [self handleCustomAction:URL];
//
//        decisionHandler(WKNavigationActionPolicyCancel);
//        return;
//    }
//    decisionHandler(WKNavigationActionPolicyAllow);
    
    
    
    NSString *strRequest = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];  //请求网址字符串
    NSLog(@"请求连接2  ,%@",strRequest);
    
    // 拦截点击链接
    //hasPrefix:方法来判断使用stringWithCString:方法创建的字符串是否以字母B开始
    if ([strRequest hasPrefix:@"http://youngplus.com.hk/"]) { //[strRequest hasPrefix:@"app://"]
        NSLog(@"不允许跳转");
        // 不允许跳转
        decisionHandler(WKNavigationActionPolicyCancel);
        
        [self handleCustomAction:strRequest];  //自定义处理URL
        
    }else if([strRequest hasPrefix:@"http://www.dnawecheck.com/"]){  // 基因检测 打开外部浏览器
        NSLog(@"不允许跳转 基因检测 打开外部浏览器");
        decisionHandler(WKNavigationActionPolicyCancel);
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strRequest]]; //打开外部浏览器
        CGFloat version = [[[UIDevice currentDevice]systemVersion]floatValue];
        if (version >= 10.0) {
            /// 大于等于10.0系统使用此openURL方法
            //打开外部浏览器
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strRequest] options:@{} completionHandler:nil];
            } else {
                // Fallback on earlier versions
            }
        } else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strRequest]];
        }
    }else {
        NSLog(@"yes 允许跳转");
        // 允许跳转
        decisionHandler(WKNavigationActionPolicyAllow);
      }
    
   
}


#pragma mark - private method
//- (void)handleCustomAction:(NSURL *)URL
//{
//    NSString *host = [URL host];
//    if ([host isEqualToString:@"scanClick"]) {
//        NSLog(@"扫一扫");
//    } else if ([host isEqualToString:@"shareClick"]) {
//        [self share:URL];
//    } else if ([host isEqualToString:@"getLocation"]) {
//        [self getLocation];
//    } else if ([host isEqualToString:@"setColor"]) {
//        [self changeBGColor:URL];
//    } else if ([host isEqualToString:@"payAction"]) {
//        [self payAction:URL];
//    } else if ([host isEqualToString:@"shake"]) {
//        [self shakeAction];
//    } else if ([host isEqualToString:@"goBack"]) {
//        [self goBack];
//    }
//
//}

- (void)handleCustomAction:(NSString *)URL
{
    // 判断跳转
    //NSString *link_id = @"";
    //用指定字符串分割字符串，返回一个数组
    NSArray *array = [URL componentsSeparatedByString:@"/"];
    //NSLog(@"分割后数组 %@",array);
    NSString *urltitle = [array lastObject];
    NSLog(@"拦截后 文章标题 %@",urltitle);
    
    
    if ([urltitle isEqualToString:@"聯絡young"]) {
        // 聯絡young
        NSLog(@"需要本地处理表单 %@",urltitle);
        aboutUsSwiftVC *vc_aboutUSswift = [[aboutUsSwiftVC alloc]init];
        [self.navigationController pushViewController:vc_aboutUSswift animated:YES];   //同一个navigationController。推出子视图
        //MMLog(@"点击了视频%@",link_id);
    }else if ([URL hasPrefix:@"app://item"]) {
        // 单品
        //MMLog(@"点击了单品%@",link_id);
    }else if ([URL hasPrefix:@"app://brand"]) {
//        // 品牌
//        link_id = [URL substringFromIndex:[NSString stringWithFormat:@"app://brand"].length];
//        MMLog(@"点击了品牌%@",link_id);
    }else{
        network *getdata = [[network alloc]init];
        [getdata itemVcgetJsonData:@"title" item:urltitle];  //获取子页面数据
        [self loadingView];  //等待网络结果动画
    }
}



#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)loadingView{  //等待网络结果动画
    
    CGRect frame = CGRectMake(0, 0, 100, 100);
    UIView *activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg.center = self.view.center;
    activityBg.backgroundColor = [UIColor grayColor];
    activityBg.alpha = 0.7;
    activityBg.layer.cornerRadius = 5.0;
    //[self.view addSubview:activityBg];
    [self.view addSubview:activityBg];
    
    UIActivityIndicatorView *loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loadActivity.frame = CGRectMake(30, 30, 40, 40);
    [loadActivity sizeToFit];
    loadActivity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [activityBg addSubview:loadActivity];
    [loadActivity startAnimating];
    //     //网络请求 延迟时间
    //    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 5000*NSEC_PER_MSEC);
    //    // 延迟方法
    //    // 1 delayTime 2 thread 3 代码
    //    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
    //        [loadActivity stopAnimating];
    //        [activityBg removeFromSuperview];
    //        [self dismissViewControllerAnimated:true completion:nil];
    ////        [self setindexdata]; //设置首页数据
    ////        [self setMenuData];
    ////        [self settableView];
    //    });
    
}

#pragma 立刻预约页面
-(void)bookingview{
    // 5 弹出框 100=40 + 60
    UIView *loginView2 = [[UIView alloc]initWithFrame:CGRectMake(UISCREEN_WIDTH - 40, (UISCREEN_HEIGHT-140)/2, UISCREEN_WIDTH, 140)];
    loginView2.backgroundColor = [UIColor clearColor];
    UIButton *bt_login2 = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, 140)];
    ////  圆角效果
    loginView2.layer.cornerRadius = 2;
    //[bt_login2 setTitle:@"--换种方式--" forState:UIControlStateNormal];
    
    //[bt_login2 setTitleColor:[UIColor colorWithRed:50/255.0 green:189/255.0 blue:170/255.0 alpha:1.0] forState:UIControlStateNormal];
    [bt_login2 addTarget:self action:@selector(applyAction1) forControlEvents:UIControlEventTouchUpInside];
    [bt_login2 setBackgroundImage:[UIImage imageNamed:@"book_40x140.png"] forState:UIControlStateNormal]; //customer_service_50x150
    [loginView2 addSubview:bt_login2];
    
    //    UIImageView *applyImg = [[UIImageView alloc]initWithFrame:CGRectMake((UISCREEN_WIDTH-40-40-20)/2, 50, 40, 40)];
    //    applyImg.image = [UIImage imageNamed:@"customer_service_50x150.png"];
    //    [bt_login2 addTarget:self action:@selector(applyAction2) forControlEvents:UIControlEventTouchUpInside];
    //    [loginView2 addSubview:applyImg];
    
    [self.view addSubview:loginView2];
    
}



-(void)applyAction1{
    if (contvc2 == nil) {
        contvc2 = [[contactTVC2 alloc]init];
    }
    [contvc2 setMenutype:1];  //设置联系我们类型，单一状态
    //[self presentViewController:vc_aboutUSswift animated:YES completion:nil];  //推一个子视图覆盖
    [self.navigationController pushViewController:contvc2 animated:YES];   //同一个navigationController。推出子视图
}
- (void)viewWillDisappear:(BOOL)animated{
    // 销毁通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"getitemDataNOTIF" object:nil];
}

@end

